import React from 'react'
import "./index.less"
import { connect } from "react-redux"
import action from '../../../store/action/ymz'
import { socket } from '../../../utils/websocket'
// uuid
import { v4 as uuidv4 } from "uuid"

import { getData } from "../../../api"

import request from '../../../utils/request'

// vant组件
import { NavBar, Cell, ImagePreview, Popup, Checkbox, Switch, Button, Toast } from "react-vant"

// 引入封装的touch事件（简单的封装touch事件）
import newTouch from "../../../utils/touch"
function FriendDetail(props) {
    // 用户信息
    const [msg] = React.useState(props.location.state.msg)
    // 总数据
    const [data] = React.useState(getData())

    // 本地存储信息
    const local = JSON.parse(localStorage.getItem('token'))
    const [isFriend, setIsFriend] = React.useState(false)
    React.useEffect(async () => {

        // 创建webSocket实例
        socket.fromId = `?user=${local.info_id}`
        socket.init()
        socket.websock.onmessage = function (messages) {
            let message = JSON.parse(messages.data)
            console.log(message, '9846532');
        }

        let newData = await data
        // 判断是否有备注
        if (!msg.remark) {
            newData.friendData.forEach(item => {
                if (item.toId === msg.info_id && local.info_id === item.fromId) {
                    msg.remark = item.remark
                }
            })
        }

        // 判断是否是好友
        setIsFriend(newData.friendData.some(item => {
            return msg.info_id === item.toId && local.info_id === item.fromId && item.state === '0'
        }))
        if (msg.info_id === local.info_id) {
            setIsFriend(false);
        }

        // onTouchStart={touchStart} onTouchMove={touchMove} onTouchEnd={touchEnd}
    }, [])


    // 发送好友请求
    const sendFriendRequest = () => {
        let id = uuidv4()
        let obj = {
            uuid: id,
            fromId: local.info_id,
            toId: msg.info_id,
            remark: remarkValue,
            state: 2,//2:等待验证  1：已拒绝  0：已同意
            isOnlyChat: false,
            isBlacklist: false,
            msg: textareaValue,
            img: msg.headPortrait,
            time: {},
            createtimes: new Date().toLocaleDateString(),
            localName: local.name,
            isRender: 1,
        }
        Toast.loading({
            message: '正在发送...',
            forbidClick: true,
            duration: 2000,
            onClose: () => {

                let ifState = request.post('/ymz/addInfoData', { obj }).then(res => {
                    console.log(res);
                    return true
                })
                if (ifState) {
                    setTimeout(() => {
                        setShowPopup(false)
                        socket.send({ to_id: msg.info_id, msg: obj })
                        Toast.info({ message: '已发送', position: "bottom" });
                    }, 1000);
                }
            }
        });
    }

    // 跳转到设置备注和标签页
    const toSetRemark = () => {
        props.history.push({
            pathname: "/main/setRemark",
            state: { data: msg, path: props.location.pathname, oldPath: props.location.state.path }
        })
    }

    // 控制是否显示申请添加朋友
    const [showPopup, setShowPopup] = React.useState(false);

    // 添加到通讯录方法
    const addAddress = () => {
        setShowPopup(true)
    }
    // 设置朋友权限
    const [value, setValue] = React.useState(['a']);
    // 是否仅聊天
    const [isOnlyChat, setIsOnlyChat] = React.useState(true)
    const toggle = (name) => {
        name === 'b' ? setIsOnlyChat(false) : setIsOnlyChat(true);
        let arr = []
        arr.push(name)
        setValue(arr);
    };
    // 申请添加好友发送朋友申请textarea value
    const [textareaValue, setTextareaValue] = React.useState('我是' + local.name + '')
    // 设置备注input value
    const [remarkValue, setRemarkValue] = React.useState(msg.name)

    // 朋友权限
    const friendJdt = () => {
        console.log('朋友权限');
    }

    // 获取main标签的ref
    const mianRef = React.useRef()

    const popupContent = React.useRef()
    return (
        <div className='friendDetail'>
            <header>
                <NavBar
                    leftArrow
                    rightText={
                        <svg className='icon search' aria-hidden='true' style={{ fontSize: "25px" }}>
                            <use xlinkHref="#icon-gengduo2"></use>
                        </svg>
                    }
                    onClickLeft={() => {
                        props.history.push({
                            pathname: props.location.state.path,
                            state: {
                                data: msg,
                                path: props.location.state.oldPath,
                                oldPath: props.location.state.old2Path,
                                old2Path: props.location.state.old3Path
                            }
                        })
                    }}
                    onClickRight={() => props.history.push({
                        pathname: "/main/dataDatumSet",
                        state: { path: props.location.pathname, oldPath: props.location.state.path, msg: props.location.state.msg }
                    })}
                />
            </header>
            <main ref={mianRef} onTouchStart={(e) => {newTouch.touchStart(e)}} onTouchMove={(e) => {newTouch.touchMove(e,mianRef)}} onTouchEnd={(e) => {newTouch.touchEnd(e,mianRef)}}>
                <div className='userBox'>
                    <div className='userBox_one_div'>
                        <div className='userBox_left'>
                            <img src={msg.headPortrait} onClick={() => {
                                ImagePreview.open({
                                    images: [
                                        msg.headPortrait
                                    ],
                                    // 开启懒加载
                                    lazyload: true,
                                    // 不显示页码数
                                    showIndex: false,
                                    // 自定义遮罩层样式
                                    overlayStyle: {
                                        background: '#000'
                                    }
                                });
                            }} alt="" />
                        </div>
                        <div className='userBox_right'>
                            {/* 用户名 */}
                            <p className='userName'>
                                <span>{isFriend ? msg.remark : msg.name}</span>
                                <svg className='icon search' aria-hidden='true' style={{ fontSize: "18px", color: msg.sex === '男' ? 'rgb(77,155,255)' : (msg.sex === '女' ? 'rgb(237,116,89)' : '#000') }}>
                                    <use xlinkHref={msg.sex === '男' ? '#icon-nanxing' : (msg.sex === '女' ? '#icon-nv' : null)}></use>
                                </svg>
                            </p>
                            {/* 昵称 */}
                            {
                                isFriend ? <p className='nickname'>
                                    昵称：<span>{msg.name}</span>
                                </p> : null
                            }
                            {/* 微信号 */}
                            {
                                isFriend ? <p className='wxNum'>
                                    微信号：<span>{msg.account}</span>
                                </p> : null
                            }
                            {/* 地区 */}
                            <p className='site'>
                                地区：<span>{msg.site}</span>
                            </p>
                        </div>
                    </div>
                    {
                        msg.info_id !== local.info_id ? <Cell title="设置备注和标签" isLink onClick={toSetRemark} /> : null
                    }
                    {
                        isFriend ? <Cell onClick={friendJdt} title="朋友权限" isLink /> : null
                    }
                </div>
                {
                    isFriend ? <div className='friendAndMsg'>

                        <Cell title="朋友圈" isLink />
                        <Cell title="更多信息" isLink />
                    </div> : (msg.info_id === local.info_id ? <Cell title="朋友圈" isLink /> : null)
                }
                <div className='bottom'>
                    {
                        isFriend ? <p onClick={() => {
                            props.history.push({
                                pathname: "/main/chatPage",
                                state: msg
                            })
                        }}>
                            <svg className='icon search' aria-hidden='true' style={{ fontSize: "20px", marginRight: '5px' }}>
                                <use xlinkHref="#icon-xiaoxi"></use>
                            </svg>
                            <span>发消息</span>
                        </p> : (msg.info_id === local.info_id ? <p>
                            <svg className='icon search' aria-hidden='true' style={{ fontSize: "20px", marginRight: '5px' }}>
                                <use xlinkHref="#icon-xiaoxi"></use>
                            </svg>
                            <span>发消息</span>
                        </p> : null)
                    }
                    {
                        isFriend ? <p>
                            <svg className='icon search' aria-hidden='true' style={{ fontSize: "20px", marginRight: '5px' }}>
                                <use xlinkHref="#icon-shexiangji"></use>
                            </svg>
                            <span>音视频通话</span>
                        </p> : null
                    }
                    {
                        msg.info_id !== local.info_id && !isFriend ? <p onClick={addAddress}>
                            <span>添加到通讯录</span>
                        </p> : null
                    }
                </div>
            </main>
            {/* 申请添加好友弹框 */}
            <Popup
                visible={showPopup}
                onClose={() => setShowPopup(false)}
                position="right"
                style={{ height: "100%", width: '100%',overflow:"hidden" }}
            >
                <NavBar
                    title="申请添加好友"
                    leftArrow
                    onClickLeft={() => {
                        setShowPopup(false)
                    }}
                />
                <div className='content' style={{ margin: '20px' }}  ref={popupContent} onTouchStart={(e) => {newTouch.touchStart(e)}} onTouchMove={(e) => {newTouch.touchMove(e,popupContent)}} onTouchEnd={(e) => {newTouch.touchEnd(e,popupContent)}}>
                    <ul>
                        <li>
                            <p style={{ paddingBottom: '5px' }}>
                                发送朋友申请
                            </p>
                            <textarea name="" id="" cols="47" rows="5" style={{
                                border: 'none',
                                background: 'rgba(0,0,0,.1)',
                                borderRadius: '7px',
                                padding: '15px',
                                boxSizing: 'border-box',
                                resize: 'none',
                            }} value={textareaValue} onChange={(e) => {
                                setTextareaValue(e.target.value);
                            }}></textarea>
                        </li>
                        <li style={{ paddingTop: '10px' }}>
                            <p style={{ paddingBottom: '5px' }}>
                                设置备注
                            </p>
                            <input type="text" style={{
                                border: 'none',
                                background: 'rgba(0,0,0,.1)',
                                borderRadius: '5px',
                                padding: '10px 15px',
                                boxSizing: 'border-box',
                                width: "100%"
                            }} value={remarkValue} onChange={(e) => {
                                setRemarkValue(e.target.value);
                            }} />
                        </li>
                        <li style={{ paddingTop: '10px' }}>
                            <p style={{ paddingBottom: '5px' }}>
                                设置朋友权限
                            </p>
                            <Checkbox.Group value={value}>
                                <Cell.Group>
                                    <Cell
                                        style={{
                                            borderRadius: '5px 5px 0px 0px',
                                            borderBottom: "1px solid rgb(229,229,229)",
                                        }}
                                        clickable
                                        title="聊天、朋友圈、微信运动等"
                                        onClick={() => toggle('a')}
                                        rightIcon={isOnlyChat ? <span className='success'></span> : null}
                                    />
                                    <Cell
                                        style={{
                                            borderRadius: '0px 0px 5px 5px',
                                        }}
                                        clickable
                                        title="仅聊天"
                                        onClick={() => toggle('b')}
                                        rightIcon={!isOnlyChat ? <span className='success'></span> : null}
                                    />
                                </Cell.Group>
                            </Checkbox.Group>
                        </li>
                        {
                            isOnlyChat ? <li style={{ paddingTop: '10px' }}>
                                <p style={{ paddingBottom: '5px' }}>
                                    朋友圈和状态
                                </p>
                                <Cell.Group>
                                    <Cell
                                        style={{
                                            background: 'rgba(0,0,0,.1)',
                                            borderRadius: '5px 5px 0px 0px',
                                            borderBottom: "1px solid rgb(168 168 168)"
                                        }}
                                        center
                                        title="不让她 / 他看我"
                                        rightIcon={
                                            <Switch size={20} inactiveColor="rgba(0,0,0,.2)" activeColor="rgb(29, 173, 108)" onChange={(checked) => console.log(`switch to ${checked}`)} />
                                        }
                                    />
                                    <Cell
                                        style={{
                                            background: 'rgba(0,0,0,.1)',
                                            borderRadius: '0px 0px 5px 5px',
                                        }}
                                        center
                                        title="不看她 / 他"
                                        rightIcon={
                                            <Switch size={20} inactiveColor="rgba(0,0,0,.2)" activeColor="rgb(29, 173, 108)" onChange={(checked) => console.log(`switch to ${checked}`)} />
                                        }
                                    />
                                </Cell.Group>

                            </li> : null
                        }
                    </ul>
                    <div className='snedBox' style={{ marginTop: "30px", display: 'flex', justifyContent: "center" }}>
                        <Button onClick={sendFriendRequest} type="info" color='rgb(29, 173, 108)' style={{ borderRadius: "5px", width: '150px' }}>发送</Button>
                    </div>
                </div>
            </Popup>
        </div>
    )
}
export default connect(state => state.ymz, action)(FriendDetail)
